package com.ideal.hadoopadmin.service.cluster;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.common.framework.orm.SearchFilter;
import com.ideal.hadoopadmin.entity.cluster.Parameter;
import com.ideal.hadoopadmin.mapper.webdb.cluster.ParameterMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 袁颖 on 2016/2/22.
 */
@Service
public class ParameterService {
    @Resource
    ParameterMapper parameterMapper;

    public PageInfo searchParameter(HttpServletRequest request, Map<String, Object> searchParams) {
        //获取当前页
        int currentPage = Integer.parseInt(request.getParameter("page") == null ? "1" : request.getParameter("page"));
        //获取where条件
        String where = SearchFilter.parseToString(searchParams);

        //分页,排序，过滤
        PageHelper.startPage(currentPage, 10, "id desc");
        PageHelper.setAppendWhere(where);
        List<Parameter> parameters = parameterMapper.findAllParameter();
        PageInfo page = new PageInfo(parameters);
        return page;
    }

    public Parameter findById(Long id) {
        return parameterMapper.findById(id);
    }

    public void saveOrUpdate(Parameter parameter) {
        if (parameter.getId() == null) {
            //无id的保存
            parameterMapper.saveParameter(parameter);
        } else {
            //有id的数据根据id更新
            parameterMapper.updateParameter(parameter);
        }
    }

    public void deleteById(Long id) {
        parameterMapper.deleteById(id);
    }

    public void deleteByParentId(Long parentId) {
        parameterMapper.deleteByParentId(parentId);
    }

    public Parameter findByKey(String parameterKey) {
        return parameterMapper.findByKey(parameterKey);
    }
    /**
     * 根据key值查询,key值为唯一
     */
    public Parameter findParameterByKey(String parameterKey) {
        return parameterMapper.findByKey(parameterKey);
    }
    public String findValueByKey(String parameterKey){
        return parameterMapper.findByKey(parameterKey).getParameterVal();
    }

    /**
     * 获取所有的参数,并以map形式存储
     * @return
     */
    public Map<String,String> getAllParameter(){
            Map<String,String> map = new HashMap<String, String>();
            List<Parameter> parameters = parameterMapper.findAllParameter();
            for(Parameter parameter:parameters){
                map.put(parameter.getParameterKey(),parameter.getParameterVal());
            }
            return map;
    }

    public List<Parameter> findParameterByParam(String parameterKey){
        return parameterMapper.findParameterByParam(parameterKey);
    }
}
